package com.pingan.generator.api.mybatis.generator.util;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成各个bean的service以及controller
 * 支持任意级目录扫描,使用时注意配置各个路径
 */
public class AutoCreateBeanUtil {

  
    // 用于被继承对象的包名
    private static final String MOUDEL_DIR = "main.resources.moudel";//model目录

    // 用于被继承对象的包名
    private static final String BASE_SERVICE_URL = "com.pingan.generator.api.service";//被继承service的基础目录
    private static final String IMPL_SERVICE_URL = "com.pingan.generator.api.service.impl";//被继承serviceImpl的基础目录
    private static final String BASE_CONTROLLER_URL = "com.pingan.generator.api.controller";//被继承action的基础目录
    private static final String BASE_MAPPER_URL = "com.pingan.generator.api.entity.mapper";//被继承action的基础目录

    private static final Map<String,String> beanMap = new HashMap<String,String>();
    static{
        beanMap.put("Service",BASE_SERVICE_URL);
        beanMap.put("ServiceImpl",IMPL_SERVICE_URL);
        beanMap.put("Controller",BASE_CONTROLLER_URL);
        beanMap.put("Mapper",BASE_MAPPER_URL);
    }


    // 公共部分
    private static final boolean PRINT_INFO_FLAG = true;// 打印信息开关
    private static final boolean PRINT_ERROR_FLAG = true;// 打印错误开关
    private static final boolean FORCE_FLAG = true;// 强制生成开关,若为true,即使文件已存在也重新生成

    public static void generatorBean(String domainObjectName){
        String[] beanNames = new String[]{"Service","ServiceImpl","Controller"};
        beanScan( domainObjectName,beanNames);
    }


    /**
     * bean文件扫描
     * 扫描指定目录下的所有java文件,生成对应的service和controller
     */
    public static void beanScan(String className,String... beanNames) {
        String fileBasePath = System.getProperty("user.dir") + "/src/main/java";
        File file = new File(fileBasePath);
        if (!file.exists()) {
            System.out.println("文件存储根目录不存在...");
            return;
        }
        if(beanNames.length<1){
            return;
        }
        try {
            for(String bean : beanNames){
                createByBean(className, fileBasePath,bean);// 创建相关类
            }
        } catch (Exception e) {
            printError(file.getAbsolutePath(), e);
        }
    }

    /**
     * 创建对应的对象
     * 创建service,serviceImpl,Controller
     * @param className 如：Employee
     * @throws Exception
     */
    public static void createByBean(String className, String fileBasePath,String beanName) throws Exception {
        String lowerFirstClassName = className.substring(0,1).toLowerCase().concat(
                className.substring(1)
        );
        String fileName = fileBasePath.replace(".", "/") + File.separator
                + beanMap.get(beanName).replace(".", "/") + File.separator
                + className + beanName +".java";
        File controllerFile = new File(fileName);
        if(!FORCE_FLAG){
            System.out.println("文件存在设置为不重新生成...");
            return;
        }
        File parentDir = new File(controllerFile.getParent());
        if(!parentDir.exists()){
            parentDir.mkdirs();
        }
        controllerFile.delete();
        String moudelJavaFile = System.getProperty("user.dir") + "/src/"+MOUDEL_DIR.replace(".","/")+File.separator+beanName+"Moudel.java";
        String fileContent = readFile(moudelJavaFile);
        if(StringUtils.isBlank(fileContent)){
            return;
        }
        fileContent = fileContent.replace("{className}",className).replace("{lowerFirstClassName}",lowerFirstClassName);
        controllerFile.createNewFile();
        FileWriter fw = new FileWriter(controllerFile, false);
        fw.write(fileContent.toString());
        fw.flush();
        fw.close();
        printLog(fileName);
    }

    public static void printLog(String info) {
        if (PRINT_INFO_FLAG) {
            System.out.println("generate file：" + info + " success！");
        }
    }

    public static void printError(String info, Exception e) {
        if (PRINT_ERROR_FLAG) {
            System.err.println("generate file：" + info + " error！Exception:"
                    + e.getMessage());
            e.printStackTrace();
        }
    }

    private static String readFile(String filePath){
        try {
            //读取文件
            FileInputStream fis = new FileInputStream(filePath);
            //fis.available():文件的长度
            byte[] b=new byte[fis.available()];
            fis.read(b);
            String fileContent = new String(b);
            System.out.println(new String(b));
            fis.close();
            return fileContent;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


}
